package com.orangeforms.webadmin.upms.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.github.pagehelper.Page;
import com.github.pagehelper.page.PageMethod;
import com.orangeforms.common.core.annotation.MyRequestBody;
import com.orangeforms.common.core.constant.ErrorCodeEnum;
import com.orangeforms.common.core.object.MyOrderParam;
import com.orangeforms.common.core.object.MyPageData;
import com.orangeforms.common.core.object.MyPageParam;
import com.orangeforms.common.core.object.ResponseResult;
import com.orangeforms.common.core.util.MyCommonUtil;
import com.orangeforms.common.core.util.MyModelUtil;
import com.orangeforms.common.core.util.MyPageUtil;
import com.orangeforms.common.log.annotation.OperationLog;
import com.orangeforms.common.log.model.constant.SysOperationLogType;
import com.orangeforms.webadmin.config.ApplicationConfig;
import com.orangeforms.webadmin.upms.dto.BusinessCollectionDto;
import com.orangeforms.webadmin.upms.model.BusinessCollection;
import com.orangeforms.webadmin.upms.service.BusinessCollectionService;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;


/**
 * 藏品管理Controller
 *
 * @Author：howlrou
 * @Date：2024/7/31 10:17
 */

@Tag(name = "藏品管理接口")
@Slf4j
@RestController
@RequestMapping("/admin/business/collection")
public class CollectionController {
    @Autowired
    private BusinessCollectionService businessCollectionService;

    @Autowired
    private ApplicationConfig applicationConfig;


    /**
     * 列出符合过滤条件的 藏品列表
     *
     * @param businessCollectionFilter 过滤对象。
     * @param orderParam               排序参数。
     * @param pageParam                分页参数。
     * @return 应答结果对象，包含查询结果集。
     */
    @SaCheckPermission("collection.list")
    @OperationLog(type = SysOperationLogType.LIST)
    @PostMapping("/list")
    public ResponseResult<MyPageData<BusinessCollectionDto>> list(
            @MyRequestBody BusinessCollection businessCollectionFilter,
            @MyRequestBody MyOrderParam orderParam,
            @MyRequestBody MyPageParam pageParam) {
        if (pageParam != null) {
            PageMethod.startPage(pageParam.getPageNum(), pageParam.getPageSize(), pageParam.getCount());
        }
        String orderBy = MyOrderParam.buildOrderBy(orderParam, BusinessCollection.class);
        List<BusinessCollection> businessCollectionList = businessCollectionService.getBusinessCollectionList(businessCollectionFilter, orderBy);
        ArrayList<BusinessCollectionDto> businessCollectionDtos = new ArrayList<>();
        long total = 0;
        if (null != businessCollectionList && !businessCollectionList.isEmpty()) {
            for (BusinessCollection businessCollection : businessCollectionList) {
                BusinessCollectionDto businessCollectionDto = MyModelUtil.copyTo(businessCollection, BusinessCollectionDto.class);
                businessCollectionDto.setCoverUrl(applicationConfig.getStaticUrl() + businessCollection.getCover());
                businessCollectionDtos.add(businessCollectionDto);
            }
            total = ((Page<BusinessCollection>) businessCollectionList).getTotal();
        }
        return ResponseResult.success(MyPageUtil.makeResponseData(businessCollectionDtos, total));
    }

//    /**
//     * 导出藏品详情列表
//     */
//    @SaCheckPermission("collection.export")
//    @OperationLog(type = SysOperationLogType.EXPORT)
//    @PostMapping("/export")
//    public void export(HttpServletResponse response, BusinessCollection zzBusinessCollection) {
//        List<ZzBusinessCollection> list = businessCollectionService.selectBusinessCollectionList(zzBusinessCollection);
//        ExcelUtil<ZzBusinessCollection> util = new ExcelUtil<ZzBusinessCollection>(ZzBusinessCollection.class);
//        util.exportExcel(response, list, "藏品详情数据");
//    }

    /**
     * 获取藏品详情详细信息
     */
    @SaCheckPermission("collection.view")
    @GetMapping(value = "/{id}")
    public ResponseResult<BusinessCollectionDto> getInfo(@PathVariable("id") Long id) {
        BusinessCollection businessCollection = businessCollectionService.selectBusinessCollectionByCollectionId(id);
        BusinessCollectionDto businessCollectionDto = new BusinessCollectionDto();
        if (null != businessCollection) {
            businessCollectionDto = MyModelUtil.copyTo(businessCollection, BusinessCollectionDto.class);
            businessCollectionDto.setCoverUrl(applicationConfig.getStaticUrl() + businessCollectionDto.getCover());
        }
        return ResponseResult.success(businessCollectionDto);
    }

    /**
     * 新增藏品详情
     */
    @SaCheckPermission("collection.add")
    @OperationLog(type = SysOperationLogType.ADD)
    @PostMapping("/add")
    public ResponseResult<Integer> add(@MyRequestBody BusinessCollection businessCollection) {
        return ResponseResult.success(businessCollectionService.insertBusinessCollection(businessCollection));
    }

    /**
     * 修改藏品详情
     */
    @SaCheckPermission("collection.update")
    @OperationLog(type = SysOperationLogType.UPDATE)
    @PostMapping("/update")
    public ResponseResult<Void> update(@MyRequestBody BusinessCollection businessCollection) {
        businessCollectionService.updateBusinessCollection(businessCollection);
        return ResponseResult.success();
    }

    /**
     * 删除藏品详情
     */
    @SaCheckPermission("collection.delete")
    @OperationLog(type = SysOperationLogType.DELETE)
    @PostMapping("/delete")
    public ResponseResult<Void> remove(@MyRequestBody Long collectionId) {
        if (MyCommonUtil.existBlankArgument(collectionId)) {
            return ResponseResult.error(ErrorCodeEnum.ARGUMENT_NULL_EXIST);
        }
        return this.doDelete(collectionId);
    }

    private ResponseResult<Void> doDelete(Long collectionId) {
        String errorMessage;
        // 验证关联Id的数据合法性
        BusinessCollection businessCollection = businessCollectionService.getById(collectionId);
        if (businessCollection == null) {
            // NOTE: 修改下面方括号中的话述
            errorMessage = "数据验证失败，当前 [对象] 并不存在，请刷新后重试！";
            return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST, errorMessage);
        }
        if (0 == businessCollectionService.deleteBusinessCollectionByCollectionId(collectionId)) {
            errorMessage = "数据操作失败，删除的对象不存在，请刷新后重试！";
            return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST, errorMessage);
        }
        return ResponseResult.success();
    }


    /**
     * 批量删除藏品信息。
     *
     * @param collectionIdList 待删除对象的主键Id列表。
     * @return 应答结果对象。
     */
    @SaCheckPermission("collection.delete")
    @OperationLog(type = SysOperationLogType.DELETE_BATCH)
    @PostMapping("/deleteBatch")
    public ResponseResult<Void> deleteBatch(@MyRequestBody List<Long> collectionIdList) {
        if (MyCommonUtil.existBlankArgument(collectionIdList)) {
            return ResponseResult.error(ErrorCodeEnum.ARGUMENT_NULL_EXIST);
        }
        for (Long userId : collectionIdList) {
            ResponseResult<Void> responseResult = this.doDelete(userId);
            if (!responseResult.isSuccess()) {
                return responseResult;
            }
        }
        return ResponseResult.success();
    }

    /**
     * 批量导入藏品信息。
     *
     * @param file
     * @return 应答结果对象。
     */
    @SaCheckPermission("collection.import")
    @OperationLog(type = SysOperationLogType.IMPORT)
    @PostMapping("/import")
    public ResponseResult<Void> uploadExcelFile(@RequestBody MultipartFile file) {
        if (file.isEmpty()) {
            return ResponseResult.error(ErrorCodeEnum.NO_EXCEL);
        }

        try {
            businessCollectionService.saveExcelData(file);
            return ResponseResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.error(ErrorCodeEnum.UPLOAD_FILE_FAILED);
        }
    }

    /**
     * 批量导入藏品信息。
     *
     * @param file
     * @return 应答结果对象。
     */
    @SaCheckPermission("collection.read")
    @OperationLog(type = SysOperationLogType.IMPORT)
    @PostMapping("/readExcelFile")
    public ResponseResult<List<BusinessCollection>> readExcelFile(@RequestBody MultipartFile file) {
        if (file.isEmpty()) {
            return ResponseResult.error(ErrorCodeEnum.NO_EXCEL);
        }

        try {
            List<BusinessCollection> businessCollectionList = businessCollectionService.readExcelData(file);
            return ResponseResult.success(businessCollectionList);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.error(ErrorCodeEnum.UPLOAD_FILE_FAILED);
        }
    }
}
